<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
    <style>
        table {
            border-collapse: collapse;
            width: 100%;
            margin-top: 20px;
        }
        
        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }
        
        th {
            background-color: #f2f2f2;
        }
        
        .form-group {
            margin-bottom: 15px;
        }
        
        .form-group label {
            display: block;
            margin-bottom: 5px;
        }
        
        .form-group input {
            width: 100%;
            padding: 8px;
            box-sizing: border-box;
        }
        
        button {
            background-color: #4CAF50;
            color: white;
            padding: 10px 15px;
            border: none;
            cursor: pointer;
            margin-right: 5px;
        }
        
        button:hover {
            background-color: #45a049;
        }
        
        .delete-btn {
            background-color: #f44336;
        }
        
        .delete-btn:hover {
            background-color: #da190b;
        }
        
        .edit-btn {
            background-color: #008CBA;
        }
        
        .edit-btn:hover {
            background-color: #007B9A;
        }
        
        .notification {
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
        }
        
        .error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
        
        .success {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        
        .hidden {
            display: none;
        }
        
        /* 弹窗样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.4);
        }
        
        .modal-content {
            background-color: #fefefe;
            margin: 15% auto;
            padding: 20px;
            border: 1px solid #888;
            width: 50%;
            max-width: 500px;
        }
        
        .close {
            color: #aaa;
            float: right;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
        }
        
        .close:hover,
        .close:focus {
            color: black;
        }
    </style>
</head>
<body>
        <nav>
        <ul style="display: flex; justify-content: space-between;">
            <div style="display: flex; justify-content: flex-start; gap: 20px;">
                <li><a href="{{ url_for('views.home') }}">首页</a></li>
                <li><a href="{{ url_for('views.about') }}">关于</a></li>
                <!-- 用户管理菜单项将根据用户权限动态显示 -->
                <li id="userManagementMenuItem" style="display: none;"><a href="{{ url_for('views.users') }}">用户管理</a></li>
            </div>
            <div>
                <li id="authSection">
                    <!-- 登录状态将通过JavaScript动态填充 -->
                </li>
            </div>
        </ul>
        </nav>
    
    <main>
        <h1>用户管理</h1>
        
        <div id="notification"></div>
        
        <div id="adminContent" class="hidden">
            <button id="addUserBtn">添加用户</button>
            
            <table id="usersTable">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>姓名</th>
                        <th>邮箱</th>
                        <th>角色</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody id="usersTableBody">
                    <!-- 用户数据将通过JavaScript动态填充 -->
                </tbody>
            </table>
        </div>
        
        <!-- 添加/编辑用户弹窗 -->
        <div id="userModal" class="modal">
            <div class="modal-content">
                <span class="close">&times;</span>
                <h2 id="modalTitle">添加用户</h2>
                <form id="userForm">
                    <input type="hidden" id="userId">
                    <div class="form-group">
                        <label for="userName">姓名:</label>
                        <input type="text" id="userName" required>
                    </div>
                    <div class="form-group">
                        <label for="userEmail">邮箱:</label>
                        <input type="email" id="userEmail" required>
                    </div>
                    <div class="form-group" id="passwordGroup">
                        <label for="userPassword">密码:</label>
                        <input type="password" id="userPassword">
                    </div>
                    <button type="submit">保存</button>
                </form>
            </div>
        </div>
        
        <div id="unauthorizedMessage" class="hidden">
            <p>您没有权限访问此页面。</p>
        </div>
    </main>

    <script>
        // 获取弹窗元素
        const modal = document.getElementById("userModal");
        const span = document.getElementsByClassName("close")[0];
        const addUserBtn = document.getElementById("addUserBtn");
        
        // 页面加载时检查登录状态
        window.addEventListener('DOMContentLoaded', function() {
            fetch('/api/users/check-login')
                .then(response => response.json())
                .then(data => {
                    const authSection = document.getElementById('authSection');
                    if (data.code === 0 && data.data.logged_in) {
                        // 检查是否是管理员
                        fetch(`/api/users/${data.data.user.id}`)
                            .then(response => response.json())
                            .then(userData => {
                                if (userData.code === 0 && userData.data.is_admin) {
                                    // 显示用户管理菜单项
                                    document.getElementById('userManagementMenuItem').style.display = 'list-item';
                                    // 显示管理员内容
                                    document.getElementById('adminContent').classList.remove('hidden');
                                    // 加载用户列表
                                    loadUsers();
                                } else {
                                    // 显示未授权消息
                                    document.getElementById('unauthorizedMessage').classList.remove('hidden');
                                }
                                
                                authSection.innerHTML = `
                                    <span>欢迎, ${data.data.user.name} | 
                                    <a href="#" onclick="logout()">登出</a></span>
                                `;
                            });
                    } else {
                        window.location.href = '/login';
                    }
                })
                .catch(error => {
                    console.error('检查登录状态失败:', error);
                });
        });
        
        // 点击添加用户按钮打开弹窗
        addUserBtn.onclick = function() {
            resetForm();
            document.getElementById('modalTitle').textContent = '添加用户';
            document.getElementById('passwordGroup').style.display = 'block';
            modal.style.display = "block";
        }
        
        // 点击关闭按钮关闭弹窗
        span.onclick = function() {
            modal.style.display = "none";
        }
        
        // 点击弹窗外部关闭弹窗
        window.onclick = function(event) {
            if (event.target == modal) {
                modal.style.display = "none";
            }
        }
        
        // 加载用户列表
        function loadUsers() {
            fetch('/api/users')
                .then(response => response.json())
                .then(data => {
                    if (data.code === 0) {
                        const usersTableBody = document.getElementById('usersTableBody');
                        usersTableBody.innerHTML = '';
                        
                        data.data.forEach(user => {
                            const row = document.createElement('tr');
                            row.innerHTML = `
                                <td>${user.id}</td>
                                <td>${user.name}</td>
                                <td>${user.email}</td>
                                <td>${user.is_admin ? '管理员' : '普通用户'}</td>
                                <td>
                                    <button class="edit-btn" onclick="editUser(${user.id})">编辑</button>
                                    ${user.is_admin ? '' : `<button class="delete-btn" onclick="deleteUser(${user.id}, '${user.name}')">删除</button>`}
                                </td>
                            `;
                            usersTableBody.appendChild(row);
                        });
                    } else {
                        showNotification('加载用户失败: ' + data.message, 'error');
                    }
                })
                .catch(error => {
                    showNotification('加载用户失败: ' + error, 'error');
                });
        }
        
        // 表单提交处理
        document.getElementById('userForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const userId = document.getElementById('userId').value;
            const name = document.getElementById('userName').value;
            const email = document.getElementById('userEmail').value;
            const password = document.getElementById('userPassword').value;
            
            const userData = {
                name: name,
                email: email
            };
            
            // 如果是创建新用户，包含密码
            if (!userId) {
                userData.password = password;
            }
            
            const url = userId ? `/api/users/${userId}` : '/api/users';
            const method = userId ? 'PUT' : 'POST';
            
            fetch(url, {
                method: method,
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(userData)
            })
            .then(response => response.json())
            .then(data => {
                if (data.code === 0) {
                    showNotification(userId ? '用户更新成功' : '用户创建成功', 'success');
                    loadUsers();
                    modal.style.display = "none";
                } else {
                    showNotification('操作失败: ' + data.message, 'error');
                }
            })
            .catch(error => {
                showNotification('操作失败: ' + error, 'error');
            });
        });
        
        // 编辑用户
        function editUser(userId) {
            fetch(`/api/users/${userId}`)
                .then(response => response.json())
                .then(data => {
                    if (data.code === 0) {
                        document.getElementById('userId').value = data.data.id;
                        document.getElementById('userName').value = data.data.name;
                        document.getElementById('userEmail').value = data.data.email;
                        document.getElementById('modalTitle').textContent = '编辑用户';
                        document.getElementById('passwordGroup').style.display = 'none';
                        modal.style.display = "block";
                    } else {
                        showNotification('获取用户信息失败: ' + data.message, 'error');
                    }
                })
                .catch(error => {
                    showNotification('获取用户信息失败: ' + error, 'error');
                });
        }
        
        // 删除用户
        function deleteUser(userId, userName) {
            const userDisplayName = userName || '该用户';
            if (confirm(`您确定要永久删除"${userDisplayName}"吗？\n\n此操作无法撤销，删除后所有相关数据将不可恢复。`)) {
                fetch(`/api/users/${userId}`, {
                    method: 'DELETE'
                })
                .then(response => response.json())
                .then(data => {
                    if (data.code === 0) {
                        showNotification(`用户"${userDisplayName}"删除成功`, 'success');
                        loadUsers();
                    } else {
                        showNotification(`删除用户"${userDisplayName}"失败: ${data.message}`, 'error');
                    }
                })
                .catch(error => {
                    showNotification(`删除用户"${userDisplayName}"失败: ${error}`, 'error');
                });
            }
        }
        
        // 重置表单
        function resetForm() {
            document.getElementById('userForm').reset();
            document.getElementById('userId').value = '';
            document.getElementById('passwordGroup').style.display = 'block';
        }
        
        // 显示通知消息
        function showNotification(message, type) {
            const notification = document.getElementById('notification');
            notification.textContent = message;
            notification.className = 'notification ' + type;
            setTimeout(() => {
                notification.textContent = '';
                notification.className = 'notification';
            }, 3000);
        }
        
        // 登出功能
        function logout() {
            fetch('/api/users/logout', {
                method: 'POST'
            })
            .then(response => response.json())
            .then(data => {
                if (data.code === 0) {
                    window.location.href = '/login';
                }
            })
            .catch(error => {
                console.error('登出失败:', error);
            });
        }
    </script>
</body>
</html>